import 'dart:convert';


import 'package:earclean/app/routes/app_pages.dart';
import 'package:earclean/app/util/common_utils.dart';
import 'package:earclean/app/util/pay_utils.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:get/get.dart';

class WebController extends GetxController {
  final url = ''.obs;

  final title = ''.obs;
  final progress = 0.0.obs;
  final canGoBack = true.obs;
  final isbase = false.obs;
  final showAddress = false.obs;

  WebViewController? webViewController;

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    if (Get.arguments != null) {
      url.value = Get.arguments['url'].toString();
      title.value = Get.arguments['title'] ?? "";
      if (Get.arguments['base'] != null && Get.arguments['base'] == true) {
        isbase.value = true;
      } else {
        isbase.value = false;
      }
      requestPermission();
    }
  }

  void requestPermission() async {
    if (isbase.value) {
      String mobile = box.read('mobile') ?? "";
      String oneKey = box.read('oneKey') ?? "";

      if (oneKey != '' || (mobile != '' && mobile != '15472626527')) {
        channel.invokeMethod('startLocation');
      } else {
        showAddress.value = false;
      }
    }
  }

  openSet() async {
    await openAppSettings();
  }

  void messageHandle(JavascriptMessage message) {
    String jsmessage = message.message;
    try {
      Map<String, dynamic> jsMap = json.decode(jsmessage);
      if (jsMap.isNotEmpty) {
        String type = jsMap["type"].toString();
        // 1、跳出APP外部在 safari 中打开，type=5,url=要打开的链接：
        // 2、内部H5跳转，type=15,url=要打开的链接
        // 3、重新获取消息未读数 type=999996：
        // 4、隐藏底部bar type=999997：
        // 5、显示底部bar type=999998：
        // 6、TD统计埋点 type=999999，两个参数：
        if (type == "5") {
          launchURL(Uri.parse(jsMap['url'].toString()));
        } else if (type == "15") {
          url.value = jsMap['url'];
          title.value = jsMap['title'] ?? "";
          Get.toNamed(Routes.WEB,
              arguments: {'url': url.value, title: title.value},
              preventDuplicates: false);
        } else if (type == "999996") {

        } else if (type == "999997") {
          canGoBack.value = true;

          // Get.find<TableController>().showAndHiddenTabbar(false);
        } else if (type == "999998") {
          canGoBack.value = false;
          // Get.find<TableController>().showAndHiddenTabbar(true);
        }else if (type == "pay") {
          PayUtils.wxpay(
            Map<String, dynamic>.from(jsMap["sign"]['data']['sign']));
          
        }
      }
    } catch (e) {
      print('prase error');
      print(e);
    }
  }

  void launchURL(Uri apkUrl) async {
    if (await canLaunchUrl(apkUrl)) {
      await launchUrl(
        apkUrl,
      );
    }
  }

  @override
  void onClose() {}
}
